package com.cnoja.jmsncn.command;

import com.cnoja.jmsncn.inf.ICommand;
import com.cnoja.jmsncn.inf.ICommander;
import com.cnoja.jmsncn.inf.IResponse;
import com.cnoja.jmsncn.kernel.exceptions.CommandException;
import com.cnoja.jmsncn.kernel.exceptions.CommandValidateException;
import com.cnoja.jmsncn.utils.text.StringUtils;

public abstract class AbstractCommand implements ICommand {

	private IResponse response = null;
	
	private ICommander commander = null;

	public ICommander getCommander() {
		return commander;
	}

	public void setCommander(ICommander commander) {
		this.commander = commander;
	}

	public IResponse getResponse() {
		return response;
	}

	public void setResponse(IResponse response) {
		this.response = response;
	}

	public AbstractCommand(String commandString) {
		this.commandString = commandString;
	}

	private boolean hasResponse = true;

	private String commandString = null;

	private ICommand next = null;

	public Long getTransactionId() {
		String[] split = this.commandString.split("\\s");
		if (split.length < 2) {
			throw new IllegalArgumentException(
					"The command has no transactionId");
		}
		return Long.valueOf(split[1].trim());
	}

	public String getCommandString() {
		return commandString;
	}

	public void setCommandString(String commandString) {
		this.commandString = commandString;
	}

	@Override
	public String toString() {
		if (StringUtils.isNullOrEmpty(this.commandString)) {
			return null;
		}
		StringBuffer buffer = new StringBuffer(this.commandString);
		buffer.append("\r\n");

		return buffer.toString();
	}

	public boolean hasResponse() {
		return this.hasResponse;
	}

	public void setHasResponse(boolean hasResponse) {
		this.hasResponse = hasResponse;

	}

	public boolean needValidate() {
		return true;
	}

	public void validateResponse(IResponse response)
			throws CommandValidateException {
	}

	@Override
	public int hashCode() {
		return this.getTransactionId().hashCode();
	}

	public boolean hasNext() {
		return this.next != null;
	}

	public ICommand getNext() {
		return this.next;
	}

	public ICommand setNext(ICommand next) {
		this.next = next;
		return this;
	}
}
